package com.jrx.anytxn.param.job.writersubject.config;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.GaAccountingCheckConfig;
import com.jrx.anytxn.param.entity.GaProductSummaryInfo;
import com.jrx.anytxn.param.entity.GaSubjectDetailInfo;
import com.jrx.anytxn.param.entity.GaSubjectSummaryInfo;
import com.jrx.anytxn.param.entity.GaSubjectTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.mapper.ext.ExtGaAccountingCheckConfigMapper;
import com.jrx.anytxn.param.mapper.ext.ExtGaProductSummaryInfoMapper;
import com.jrx.anytxn.param.mapper.ext.ExtGaSubjectDetailInfoMapper;
import com.jrx.anytxn.param.mapper.ext.ExtGaSubjectSummaryInfoMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import com.jrx.anytxn.param.mapper.ext.ExtSubjectTableMapper;
import com.jrx.anytxn.param.service.account.ISubjectTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 读取账务流水 文件 将数据导入数据库
 *
 * @author xqy
 * @version 1.0
 * @date 2019/11/29
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class SubjectFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(SubjectFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Resource
    private ExtGaSubjectDetailInfoMapper extGaSubjectDetailInfoMapper;

    @Autowired
    private PathFileConfig pathFileConfig;

    @Autowired
    private ISegmentService iSegmentService;

    @Resource
    private ExtGaSubjectSummaryInfoMapper extGaSubjectSummaryInfoMapper;

    @Resource
    private ExtGaProductSummaryInfoMapper extGaProductSummaryInfoMapper;

    @Resource
    private ExtGaAccountingCheckConfigMapper extGaAccountingCheckConfigMapper;

    @Resource
    private ExtSubjectTableMapper extSubjectTableMapper;

    @Resource
    private ISubjectTableService subjectTableService;
    @Autowired
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;
    @Autowired
    private ISegmentService segmentService;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;

    @Bean
    public Job readerFileJob() throws IOException {
        return jobBuilderFactory.get("readerFileJob")
                .start(readerDetailFileStep())
                .next(writeSummaryStep())
                .next(readerProductFileStep())
                .next(cutEndStep())
                .build();
    }

    @Bean
    public Step readerDetailFileStep() throws IOException {
        return stepBuilderFactory.get("readerDetailFileStep").tasklet(readerDetailFileTasklet()).build();
    }

    @Bean
    public Tasklet readerDetailFileTasklet() {

        return (stepContribution, chunkContext) -> {
            List<GaSubjectDetailInfo> gaSubjectDetailInfoList = new ArrayList<>();
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String businessDate = DateUtils.format(org.getToday(),"yyyyMMdd");
            String subjectDetailPage = pathFileConfig.getBasePath() + "/subjectDetail/" + org.getTenantId();
            logger.info("科目流水表请求的目录为:{},业务日期为:{}", subjectDetailPage, businessDate);

            File dirFile = new File(subjectDetailPage);
            if (dirFile.exists()) {
                File[] files = dirFile.listFiles();
                for (File file : Objects.requireNonNull(files)) {
                    //如果遇到文件夹则递归调用。
                    if (!file.isDirectory() && file.getName().contains(businessDate) && file.getName().contains(".txt") && file.getName().contains("detailBatch")) {
                        String subjectDetailPah;
                        //如果传递过来的参数dirFile是以文件分隔符，也就是/或者\结尾，则如此构造
                        if (dirFile.getPath().endsWith(File.separator)) {
                            subjectDetailPah = dirFile.getPath() + file.getName();
                        } else {
                            //否则，如果没有文件分隔符，则补上一个文件分隔符，再加上文件名，才是路径
                            subjectDetailPah = dirFile.getPath() + File.separator + file.getName();
                        }
                        /* 读入TXT文件 */
                        InputStreamReader reader = new InputStreamReader(new FileInputStream(subjectDetailPah), StandardCharsets.UTF_8); // 建立一个输入流对象reader
                        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
                        String line = br.readLine();
                        while (line != null) {
                            GaSubjectDetailInfo gaSubjectDetailInfo = JsonUtils.json2pojo(line, GaSubjectDetailInfo.class);
                            //判断是否有数据
                            if (gaSubjectDetailInfo != null) {
                                gaSubjectDetailInfoList.add(gaSubjectDetailInfo);
                            }
                            line = br.readLine(); // 一次读入一行数据
                        }
                    }
                }
            }
            if (!gaSubjectDetailInfoList.isEmpty()) {
                List<GaSubjectDetailInfo> gaSubjectDetailInfos = this.mergeSubjectDetailInfoList(gaSubjectDetailInfoList);

                //更新余额
                this.updateBal(gaSubjectDetailInfos, org.getLastProcessingDate());

                for (GaSubjectDetailInfo gaSubjectDetailInfo : gaSubjectDetailInfos) {
                    //判断库里是否有数据
                    GaSubjectDetailInfo gaSubjectDetail = extGaSubjectDetailInfoMapper.selectByUnique(gaSubjectDetailInfo.getSubjectId(), gaSubjectDetailInfo.getTenantId(), gaSubjectDetailInfo.getDetailDate());
                    //没有执行添加 有执行修改
                    if (gaSubjectDetail == null) {
                        gaSubjectDetailInfo.setRecordVersionNumber(Constant.VERSION_NUMBER);
                        gaSubjectDetailInfo.setId(iSegmentService.getId("GaSubjectDetailInfo"));
                        extGaSubjectDetailInfoMapper.insertSelective(gaSubjectDetailInfo);
                    } else {
                        gaSubjectDetailInfo.setId(gaSubjectDetail.getId());
                        extGaSubjectDetailInfoMapper.updateByPrimaryKeySelective(gaSubjectDetailInfo);
                    }
                }
            }
            return RepeatStatus.FINISHED;
        };
    }

    /**
     * 更新科目借贷余额
     * @param gaSubjectDetailInfos
     * @return
     */
    private void updateBal(List<GaSubjectDetailInfo> gaSubjectDetailInfos,Date lastDate) {
        gaSubjectDetailInfos.forEach( ga -> {
                    GaSubjectDetailInfo lastDetail = extGaSubjectDetailInfoMapper.selectByUnique(ga.getSubjectId(),ga.getTenantId(),lastDate);
                    BigDecimal creditBal = BigDecimal.ZERO;
                    BigDecimal debitBal = BigDecimal.ZERO;
                    if(null != lastDetail){
                         creditBal = lastDetail.getCreditBal();
                         debitBal = lastDetail.getDebitBal();
                    }
                    ga.setCreditBal(creditBal.add(ga.getCreditAmount()));
                    ga.setDebitBal(debitBal.add(ga.getDebitAmount()));
                }
        );
    }


    @Bean
    public Step writeSummaryStep() {
        return stepBuilderFactory.get("writeSummaryStep").tasklet(writeSummaryTasklet()).build();
    }

    private Tasklet writeSummaryTasklet() {

        return (stepContribution, chunkContext) -> {
            List<GaSubjectTable> allSubject = subjectTableService.getAllSubjectId(Constant.STATUS_1);
            if (org.springframework.util.CollectionUtils.isEmpty(allSubject)) {
                return RepeatStatus.FINISHED;
            }

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            Date today = org.getToday();
            //获取 当前 处理业务日期的月份
            String month = DateUtils.format(today,"yyyyMM");
            // 获取上月的月份
            String lastMonth = DateUtils.format(DateUtils.add(today, Calendar.MONTH, -1),"yyyyMM");
            //科目号集合不为空时
            List<GaSubjectSummaryInfo> insertList = new ArrayList<>();
            List<GaSubjectSummaryInfo> updateList = new ArrayList<>();

            for (GaSubjectTable subject : allSubject) {
                GaSubjectSummaryInfo newSubjectSummary = new GaSubjectSummaryInfo();
                //将月份，机构号，科目号放到 科目总账对象中
                newSubjectSummary.setSummaryMonth(month);
                //机构号
                newSubjectSummary.setOrganizationId(subject.getOrganizationId());
                //科目号
                newSubjectSummary.setSubjectId(subject.getSubjectId());
                newSubjectSummary.setTenantId(subject.getTenantId());
                //判断当前月份是否存在数据
                GaSubjectSummaryInfo oldSummaryInfo = extGaSubjectSummaryInfoMapper.selectByUnique(subject.getSubjectId(),subject.getTenantId(), month);
                //获取当天明细
                GaSubjectDetailInfo gaSubjectDetail = extGaSubjectDetailInfoMapper.selectByUnique(subject.getSubjectId(), subject.getTenantId(),today);
                int debitcount = 0;
                int creditCount = 0;
                BigDecimal debitAmount = BigDecimal.ZERO;
                BigDecimal creditAmount =  BigDecimal.ZERO;
                if(null != gaSubjectDetail){
                    debitcount = gaSubjectDetail.getDebitCount();
                    creditCount = gaSubjectDetail.getCreditCount();
                    debitAmount = gaSubjectDetail.getDebitAmount();
                    creditAmount = gaSubjectDetail.getCreditAmount();
                }

                if (null == oldSummaryInfo) {
                    //月初
                    newSubjectSummary.setId(iSegmentService.getId("GaSubjectSummaryInfo"));
                    newSubjectSummary.setUpdateBy("subjectSummary");
                    newSubjectSummary.setRecordVersionNumber(Constant.VERSION_NUMBER);
                    newSubjectSummary.setLastMonthDebitBal(BigDecimal.ZERO);
                    newSubjectSummary.setLastMonthCreditBal(BigDecimal.ZERO);
                    //获取上月的科目总账数据
                    GaSubjectSummaryInfo lastSubjectSummaryInfo = extGaSubjectSummaryInfoMapper.selectByUnique(subject.getSubjectId(), subject.getTenantId(),lastMonth);
                    if (null != lastSubjectSummaryInfo) {
                        //上月存在
                        newSubjectSummary.setLastMonthDebitBal(lastSubjectSummaryInfo.getDebitBal());
                        newSubjectSummary.setLastMonthCreditBal(lastSubjectSummaryInfo.getCreditBal());
                    }
                    newSubjectSummary.setDebitCount(debitcount);
                    newSubjectSummary.setCreditCount(creditCount);
                    newSubjectSummary.setDebitAmount(debitAmount);
                    newSubjectSummary.setCreditAmount(creditAmount);
                    newSubjectSummary.setDebitBal(newSubjectSummary.getLastMonthDebitBal().add(debitAmount));
                    newSubjectSummary.setCreditBal(newSubjectSummary.getLastMonthCreditBal().add(creditAmount));
                    insertList.add(newSubjectSummary);
                } else {
                    //存在则更新
                    newSubjectSummary.setId(oldSummaryInfo.getId());
                    newSubjectSummary.setDebitCount(oldSummaryInfo.getDebitCount() + debitcount);
                    newSubjectSummary.setCreditCount(oldSummaryInfo.getCreditCount() + creditCount);
                    newSubjectSummary.setDebitAmount(oldSummaryInfo.getDebitAmount().add(debitAmount));
                    newSubjectSummary.setCreditAmount(oldSummaryInfo.getCreditAmount().add(creditAmount));
                    newSubjectSummary.setDebitBal(oldSummaryInfo.getDebitBal().add(debitAmount));
                    newSubjectSummary.setCreditBal(oldSummaryInfo.getCreditBal().add(creditAmount));
                    updateList.add(newSubjectSummary);
                }
             }

            if(CollectionUtils.isNotEmpty(insertList)) {
                extGaSubjectSummaryInfoMapper.batchInsert(insertList);
            }
            if(CollectionUtils.isNotEmpty(updateList)) {
                extGaSubjectSummaryInfoMapper.batchUpdateForBatch(updateList);
            }

            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Step readerProductFileStep() {
        return stepBuilderFactory.get("readerProductFileStep").tasklet(readerProductFileTasklet()).build();
    }

    private Tasklet readerProductFileTasklet() {

        return (stepContribution, chunkContext) -> {
            List<GaProductSummaryInfo> gaProductSummaryInfoList = new ArrayList();
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String businessDate = DateUtils.format(org.getToday(),"yyyyMMdd");
            String productSummaryPath = pathFileConfig.getBasePath() + "/productSummary/" + org.getTenantId();
            logger.info("产品汇总表请求的目录为:{},业务日期为:{}", productSummaryPath, businessDate);
            //获取科目
            File dirFile = new File(productSummaryPath);
            if (dirFile.exists()) {
                File[] files = dirFile.listFiles();
                for (File file : Objects.requireNonNull(files)) {
                    //如果遇到文件夹则递归调用。
                    if (!file.isDirectory() && file.getName().contains(businessDate) && file.getName().contains(".txt") && file.getName().contains("productSummary")) {
                        String productSummaryPah;
                        //如果传递过来的参数dirFile是以文件分隔符，也就是/或者\结尾，则如此构造
                        if (dirFile.getPath().endsWith(File.separator)) {
                            productSummaryPah = dirFile.getPath() + file.getName();
                        } else {
                            //否则，如果没有文件分隔符，则补上一个文件分隔符，再加上文件名，才是路径
                            productSummaryPah = dirFile.getPath() + File.separator + file.getName();
                        }
                        /* 读入TXT文件 */

                        InputStreamReader reader = new InputStreamReader(new FileInputStream(productSummaryPah), StandardCharsets.UTF_8); // 建立一个输入流对象reader
                        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
                        String line = br.readLine();
                        while (line != null) {
                            GaProductSummaryInfo gaProductSummaryInfo = JsonUtils.json2pojo(line, GaProductSummaryInfo.class);
                            if (gaProductSummaryInfo != null) {
                                gaProductSummaryInfoList.add(gaProductSummaryInfo);

                            }
                            line = br.readLine(); // 一次读入一行数据
                        }
                    }
                }
            }
            if (CollectionUtils.isEmpty(gaProductSummaryInfoList)) {
                return RepeatStatus.FINISHED;
            }

            List<GaProductSummaryInfo> gaProductSummaryInfos = this.mergeProductSummaryInfoList(gaProductSummaryInfoList, org.getToday());
            extGaProductSummaryInfoMapper.batchInsert(gaProductSummaryInfos);
            return RepeatStatus.FINISHED;
        };
    }



    /**
     * 根据科目号合并流水表
     *
     * @param gaSubjectDetailInfoList
     * @return
     */
    private List<GaSubjectDetailInfo> mergeSubjectDetailInfoList(List<GaSubjectDetailInfo> gaSubjectDetailInfoList) {
        List<GaSubjectDetailInfo> gaSubjectDetailInfos = new ArrayList<>();
        //根据科目号合并集合的值
        gaSubjectDetailInfoList.stream().collect(Collectors.groupingBy(GaSubjectDetailInfo::getSubjectId, Collectors.toList())).forEach(
                (id, transfer) -> transfer.stream().reduce((a, b) -> {
                    GaSubjectDetailInfo subjectDetailInfo = new GaSubjectDetailInfo();
                    subjectDetailInfo.setTenantId(a.getTenantId());
                    subjectDetailInfo.setOrganizationId(a.getOrganizationId());
                    subjectDetailInfo.setDetailDate(a.getDetailDate());
                    subjectDetailInfo.setSubjectId(a.getSubjectId());
                    subjectDetailInfo.setUpdateBy(a.getUpdateBy());
                    subjectDetailInfo.setDebitAmount(a.getDebitAmount().add(b.getDebitAmount()));
                    subjectDetailInfo.setDebitCount(a.getDebitCount() + b.getDebitCount());
                    subjectDetailInfo.setCreditAmount(a.getCreditAmount().add(b.getCreditAmount()));
                    subjectDetailInfo.setCreditCount(a.getCreditCount() + b.getCreditCount());
                    return subjectDetailInfo;
                }).ifPresent(gaSubjectDetailInfos::add)
        );
        return gaSubjectDetailInfos;
    }

    /**
     * 根据科目号合并流水表
     *
     * @param gaProductSummaryInfoList
     * @return
     */
    private List<GaProductSummaryInfo> mergeProductSummaryInfoList(List<GaProductSummaryInfo> gaProductSummaryInfoList, Date bussinessDate) {
        List<GaProductSummaryInfo> gaProductSummaryInfos = new ArrayList<>();
        //根据科目号合并集合的
        gaProductSummaryInfoList.stream().collect(Collectors.groupingBy(GaProductSummaryInfo::getProductId, Collectors.toList())).forEach(
                (id, infoList) -> {
                    GaProductSummaryInfo productSummaryInfo = infoList.stream().reduce(infoList.get(0), (a, b) -> {

                        if(b.getId().equals(a.getId())){
                            return a;
                        }
                        try {
                            a.setId(iSegmentService.getId("GaProductSummaryInfo"));
                        } catch (SegmentException e) {
                            throw new RuntimeException(e);
                        }
                        a.setNomalPrinBal(a.getNomalPrinBal().add(b.getNomalPrinBal()));
                        a.setOverDuePrinBal(a.getOverDuePrinBal().add(b.getOverDuePrinBal()));
                        a.setDeadPrinBal(a.getDeadPrinBal().add(b.getDeadPrinBal()));
                        a.setBadPrinBal(a.getBadPrinBal().add(b.getBadPrinBal()));
                        a.setNomalIntrBal(a.getNomalIntrBal().add(b.getNomalIntrBal()));
                        a.setOverDueIntrBal(a.getOverDueIntrBal().add(b.getOverDueIntrBal()));
                        a.setPentIntrBal(a.getPentIntrBal().add(b.getPentIntrBal()));
                        a.setCompIntrBal(a.getCompIntrBal().add(b.getCompIntrBal()));
                        a.setAccuIntrBal(a.getAccuIntrBal().add(b.getAccuIntrBal()));
                        a.setAccuPentIntrBal(a.getAccuPentIntrBal().add(b.getAccuPentIntrBal()));
                        a.setAccuCompIntrBal(a.getAccuCompIntrBal().add(b.getAccuCompIntrBal()));
                        a.setClassify1PrinBal(a.getClassify1PrinBal().add(b.getClassify1PrinBal()));
                        a.setClassify2PrinBal(a.getClassify2PrinBal().add(b.getClassify2PrinBal()));
                        a.setClassify3PrinBal(a.getClassify3PrinBal().add(b.getClassify3PrinBal()));
                        a.setClassify4PrinBal(a.getClassify4PrinBal().add(b.getClassify4PrinBal()));
                        a.setClassify1ImpairmentBal(a.getClassify1ImpairmentBal().add(b.getClassify1ImpairmentBal()));
                        a.setClassify2ImpairmentBal(a.getClassify2ImpairmentBal().add(b.getClassify2ImpairmentBal()));
                        a.setClassify3ImpairmentBal(a.getClassify3ImpairmentBal().add(b.getClassify3ImpairmentBal()));
                        a.setClassify4ImpairmentBal(a.getClassify4ImpairmentBal().add(b.getClassify4ImpairmentBal()));
                        return a;
                    });

                    String productId = infoList.get(0).getProductId();
                    String tenantId = infoList.get(0).getTenantId();
                    GaAccountingCheckConfig checkConfig = extGaAccountingCheckConfigMapper.selectByProductIdAndTenantId(productId, tenantId);
                    if(null == checkConfig){
                        gaProductSummaryInfos.add(productSummaryInfo);
                        return;
                    }
                    Method[] methods = ReflectionUtils.getAllDeclaredMethods(GaAccountingCheckConfig.class);

                    List<Method> methodList = Arrays.stream(methods)
                            .filter(method -> method.getName().startsWith("get"))
                            .filter(method -> method.getName().endsWith("SubjectId")).collect(Collectors.toList());

                    methodList.forEach(method -> {
                                try {
                                    Object obj = method.invoke(checkConfig);
                                    if(null == obj){
                                        return;
                                    }
                                    String subjectId = (String)obj;
                                    GaSubjectDetailInfo detailInfo = extGaSubjectDetailInfoMapper.selectByUnique(subjectId, tenantId, bussinessDate);
                                    GaSubjectTable gaSubjectTable = extSubjectTableMapper.selectBySubjectIdAndTenId(tenantId, subjectId);
                                    BigDecimal accountingAmt = BigDecimal.ZERO;
                                    if(null != detailInfo) {
                                        if ("C".equals(gaSubjectTable.getBalDirection())) {
                                            accountingAmt = detailInfo.getCreditBal().subtract(detailInfo.getDebitBal());
                                        } else {
                                            accountingAmt = detailInfo.getDebitBal().subtract(detailInfo.getCreditBal());
                                        }
                                    }

                                    String methodName = method.getName().substring(3);
                                    String accountingMethodName = "setAccounting" + methodName.substring(0, methodName.indexOf("S")) + "Bal";
                                    Method accountingMethod = GaProductSummaryInfo.class.getMethod(accountingMethodName, BigDecimal.class);
                                    accountingMethod.invoke(productSummaryInfo, accountingAmt);
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                            }
                    );
                    gaProductSummaryInfos.add(productSummaryInfo);
                }
        );
        return gaProductSummaryInfos;
    }

    @Bean
    public Step cutEndStep() {
        return stepBuilderFactory.get("cutEndStep").tasklet(cutEndStepTasklet()).build();
    }

    private Tasklet cutEndStepTasklet() {

        return (stepContribution, chunkContext) -> {
            //获取业务日期
            PrOrganizationTable org = extPrOrganizationTableMapper.selectByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            BtBatchStatus batchStatus = extBtBatchStatusMapper.selectByStatusAndJobName(Constant.BATCH_SATTUS_2, Constant.ABLE_TO_REPORT, org.getTenantId(), org.getToday());
            if (Objects.isNull(batchStatus)) {
                BtBatchStatus btBatchStatus = new BtBatchStatus();
                try {
                    btBatchStatus.setId(segmentService.getId(Constant.BT_BATCH_STATUS_ID));//id
                } catch (SegmentException e) {
                    logger.error("主键生成错误", e);
                    throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
                }
                btBatchStatus.setBatchStatus(Constant.BATCH_SATTUS_2);//状态 执行完成
                btBatchStatus.setBusinessDate(org.getToday());//当前业务日期
                btBatchStatus.setJobName(Constant.ABLE_TO_REPORT);//批处理名称
                btBatchStatus.setTenantId(org.getTenantId());//租户id
                btBatchStatus.setUpdateBy(Constant.DEFAULT_USER);
                btBatchStatus.setRecordVersionNumber(Constant.VERSION_NUMBER);//初始版本号
                extBtBatchStatusMapper.insertSelective(btBatchStatus);
            }
            return RepeatStatus.FINISHED;
        };
    }
}